import './imports'
import Header from '../components/Header';
import NavBar from '../components/NavBar';
import { NEWS_TYPE } from '../data';
import NewsList from '../components/NewsList';
import services from '../services/index';
import { scrollToBottom, getItemNode } from '../libs/utils';
import PageLoading from '../components/PageLoading';
import MoreLoading from '../components/MoreLoading';

((doc) => {
    const oApp = document.querySelector('#app')
    const config = {
        type: 'top',
        count: 10,
        pageNum: 0,
        isLoading: false
    }
    let oNewsListWrapper = null;  //因为多处用到顾在全局声明
    let t = null;
    const newsData = {};


    const init = async () => {
        render();
        await setNewsList();
        bindEvent();
    }

    //操作DOM生成页面
    function render() {
        //头部DOM生成
        const headerTpl = Header.tpl({
            url: 'index.html',
            title: '移动端新闻（个人学习前端用）',
            showLeftIcon: false,
            showRightIcon: true
        });
        //导航栏DOM生成
        const navBarTpl = NavBar.tpl(NEWS_TYPE)
        //新闻列表外层容器生成
        const newsListWrapper = NewsList.wrapperTpl(82);
        //加入主文档
        oApp.innerHTML += (headerTpl + navBarTpl + newsListWrapper);

        //渲染页面时即把全局中的oNewsListWrapper改变
        oNewsListWrapper = oApp.querySelector('.news-list')
    }

    //绑定事件处理函数
    function bindEvent() {
        //导航栏点击切换type
        NavBar.bindEvent(setType);
        oNewsListWrapper.addEventListener('click', goToDetail, false);
        window.addEventListener('scroll', scrollToBottom.bind(null, getMoreList), false);
    }

    //获取首页要展示的新闻数据
    async function setNewsList() {
        const { type, count, pageNum } = config;
        if (newsData[type]) {
            console.log('from pool');
            renderNewsList(newsData[type][pageNum]);
            return;
        }
        oNewsListWrapper.innerHTML = PageLoading.tpl();
        const res = await services.getNewsList(type, count);
        if (res == 404) { return; }
        newsData[type] = res;
        setTimeout(() => {
            oNewsListWrapper.innerHTML = '';
            renderNewsList(newsData[type][pageNum]);
        }, 300);

    }
    //加载更多
    function getMoreList() {
        //为了防止频繁触发探底事件 加上isLoading这个锁
        if (!config.isLoading) {
            config.pageNum++;
            clearTimeout(t);
            const { pageNum, type } = config;
            if (pageNum >= newsData[type].length) {
                MoreLoading.add(oNewsListWrapper, false);
                return;
            } else {
                config.isLoading = true;
                MoreLoading.add(oNewsListWrapper, true);
                t = setTimeout(() => {
                    setNewsList();
                }, 300);
            }
        }
    }


    //渲染首页新闻列表
    function renderNewsList(data) {
        const { pageNum } = config;
        const newsListTpl = NewsList.tpl({
            data,
            pageNum
        });
        MoreLoading.remove(oNewsListWrapper);
        oNewsListWrapper.innerHTML += newsListTpl;
        config.isLoading = false;
    }

    //提取选中项数据并保存到localstorage中
    function setCurrentNew(options) {
        const { idx, pageNum } = options;
        const currentNew = newsData[config.type][pageNum][idx];
        localStorage.setItem('currentNew', JSON.stringify(currentNew))
    }
    function goToDetail(ev) {
        /* 
        要找到对应的新闻，需根据item标签中的pageNum和index这两个数据去列表中找，
        const oItem = arguments[1].target;
        但是这里拿到的oItem并不能确保是想要的item标签项
        因为有可能点的是author或者title等标签。这时候要写个函数getItemNode处理下，确保拿到的是news-item标签
        */
        const oItem = getItemNode(ev.target);
        const options = {
            idx: oItem.dataset.index,
            pageNum: oItem.dataset.page
        }
        setCurrentNew(options);
        window.location.href = `detail.html?path=${location.pathname}`;
    }

    function setType(type) {
        config.type = type;
        config.pageNum = 0;
        config.isLoading = false;
        oNewsListWrapper.innerHTML = '';
        setNewsList();
    }



    init();
})(document);